package org.tio.im.server.command.handler;

import com.alibaba.fastjson.JSONObject;
import org.tio.core.ChannelContext;
import org.tio.im.common.ImAio;
import org.tio.im.common.ImPacket;
import org.tio.im.common.http.HttpRequest;
import org.tio.im.common.packets.ChatBody;
import org.tio.im.common.packets.ChatType;
import org.tio.im.common.packets.Command;
import org.tio.im.common.packets.RespBody;
import org.tio.im.common.utils.ChatKit;
import org.tio.im.server.command.AbCmdHandler;
import org.tio.utils.lock.SetWithLock;

import java.util.HashMap;
import java.util.Map;

public class OrderNotifyReqHandler extends AbCmdHandler {

    @Override
    public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception {

        ChatBody chatBody = null;
        if (packet instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest) packet;
            Map<String, Object[]> params = httpRequest.getParams();
            if (!params.isEmpty()) {
                Object[] defaultObjs = {""};
                Object userid = params.getOrDefault("userid", defaultObjs)[0];
                Map<String, Object> contentParam = new HashMap<>();
                for (Map.Entry<String, Object[]> entry : params.entrySet()) {
                    contentParam.put(entry.getKey(), entry.getValue()[0]);
                }
                String msgContent = JSONObject.toJSONString(contentParam);
                chatBody = new ChatBody();
                chatBody.setFrom("订单回调");
                chatBody.setChatType(ChatType.CHAT_TYPE_PRIVATE.getNumber());
                chatBody.setContent(msgContent);
                chatBody.setTo(userid.toString());
                chatBody.setMsgType(0);
            }
        }


        if (chatBody == null) {
            throw new Exception("request is null");
        }
        ImPacket chatPacket = new ImPacket(Command.COMMAND_CHAT_REQ, new RespBody(Command.COMMAND_CHAT_REQ, chatBody.toJsonString()).toByte());
        //私聊
        SetWithLock<ChannelContext> toChannelContexts = ImAio.getChannelContextsByUserid(channelContext.getGroupContext(), chatBody.getTo());
        if (toChannelContexts != null && toChannelContexts.size() > 0) {
            ImAio.send(toChannelContexts, chatPacket);
            //发送成功响应包
            return ChatKit.sendSuccessRespPacket(channelContext);
        } else {
            //用户不在线响应包
            return ChatKit.offlineRespPacket(channelContext);
        }
    }

    @Override
    public Command command() {
        return Command.COMMAND_CHAT_REQ;
    }
}
